﻿using System;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace Quiki.Looki
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private FileSystemWatcher watcher;

        public MainWindow()
        {
            InitializeComponent();
        }

        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);

            GenerateInitialView();
            CreateFileWatch();
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (watcher != null)
            {
                watcher.EnableRaisingEvents = false;
                watcher.Dispose();
                watcher = null;
            }

            base.OnClosing(e);
        }

        private void GenerateInitialView()
        {
            string fullPath = ProcessWikiText();
            Browser.Navigate(new Uri("file://" + fullPath));
        }

        private void CreateFileWatch()
        {
            watcher = new FileSystemWatcher(
                Path.GetFullPath(@"..\..\..\Docs\TemplatesDocs"), 
                "Include File.wiki");
            watcher.Changed += OnWikiFileChanged;
            watcher.EnableRaisingEvents = true;
        }

        private void OnWikiFileChanged(object sender, FileSystemEventArgs fileSystemEventArgs)
        {
            ProcessWikiText();

            if (Browser.Dispatcher.CheckAccess())
                RefreshBrowser();
            else
                Browser.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(RefreshBrowser));
        }

        private void RefreshBrowser()
        {
            Browser.Refresh();
        }

        private static string ProcessWikiText()
        {
            DocumentProcessorSettings settings = new DocumentProcessorSettings();
            settings.InputDir = @"..\..\..\Docs";
            settings.InputFilter = @"Include File.wiki";
            settings.OutputDir = "QuikiDocs";
            settings.TemplateFileName = @"..\..\..\Docs\template.vm.html";
            settings.GenerateParsingInfoFiles = false;

            ILogger logger = new ConsoleLogger();
            DocumentProcessor processor = new DocumentProcessor(settings, logger);

            for (int i = 0; i < 3; i++)
            {
                try
                {
                    processor.Process();
                    break;
                }
                catch (IOException)
                {
                    Thread.Sleep(500);
                }
            }

            return Path.GetFullPath("QuikiDocs/TemplatesDocs/Include_File.html");
        }
    }
}
